﻿using System;
using System.Data;
using Business;
using Common.Constant;
using Blog.Common.Helpers;

public partial class Template : System.Web.UI.MasterPage
{
    private CategoryBus _categoryBus;
    private UsersBus _usersBus;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["User"] == null)
        {
            pnLogin.Visible = true;
            pnLogout.Visible = false;
        }
        else
        {
            pnLogin.Visible = false;
            pnLogout.Visible = true;
            LabelUser.Text = Session["User"].ToString();
            if (Session["Role"].ToString() == DBSchemas.AdminRoleName)
            {
                LinkButtonAdmin.Visible = true;
                LinkUserManager.Enabled = true;
                LinkCategoryManager.Enabled = true;
            }
            else
            {
                LinkCategoryManager.Text = ".........................";
                LinkUserManager.Text = ".........................";
            }
        }
        if(!IsPostBack)
        {
            LoadCategory();
        }
    }

    protected void LoadCategory()
    {
        _categoryBus = new CategoryBus();
        var data = _categoryBus.SelectAllCategory();
        RepeaterCategory.DataSource = data;
        RepeaterCategory.DataBind();
    }

    protected void ButtonLoginClick(object sender, EventArgs e)
    {
        try
        {
            string password = CryptographyHelper.EncryptPassword(txtPassword.Text.Trim());
            _usersBus = new UsersBus();
            bool result = _usersBus.CheckUserLogOn(txtUserName.Text.Trim().ToLower(), password);
            if(result)
            {
                Session["User"] = txtUserName.Text;
                pnLogin.Visible = false;
                pnLogout.Visible = true;
                LabelUser.Text = Session["User"].ToString();
                DataSet dataSet = _usersBus.GetUserByUserName(txtUserName.Text);
                Session["Role"] = dataSet.Tables[0].Rows[0]["IsAdmin"].ToString() == "True" ? DBSchemas.AdminRoleName : DBSchemas.UserRoleName;
                Response.Redirect(Request.RawUrl);
            }
            else
            {
                lblMessage.Text = UIMessage.InvalidUserNameOrPassword;
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }  
    }

    protected void LinkButtonLogoutClick(object sender, EventArgs e)
    {
        Session.Abandon();
        Response.Redirect("~/Default.aspx");
    }
}
